package com.itanqing.demo.study05;



import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.time.Duration;
import java.time.Instant;

public class ZeroCopyClient {

    public static void main(String[] args) throws Exception {

        SocketChannel open = SocketChannel.open();
        boolean connect = open.connect(new InetSocketAddress(7001));

        // 获取文件Channel
        File file = new File("src/main/resources/01.jpeg");
        FileChannel channel = new FileInputStream(file).getChannel();

        Instant startTime = Instant.now();

        /*
         * 在Linux下,一个transferTo方法就可以传输完成
         * 在Windows下,调用一次transferTo 只能传输8M,就需要分段传输文件,而且要记录传输时的位置
         * transferTo 底层使用零拷贝
         */
        long l = channel.transferTo(0, channel.size(), open);
        System.out.println(l);

        Instant endTime = Instant.now();
        System.out.println("用时:" + Duration.between(startTime,endTime).toMillis() + "ms");
        channel.close();
    }

}

